﻿using System;
using System.Collections.Generic;
using Caliburn.Micro;
using Chicken4wp.Services;
using Chicken4wp.ViewModels;
using System.Reflection;
using Caliburn.Micro.BindableAppBar;
using System.Windows.Controls;

namespace Chicken4wp
{
    public class AppBootstrapper : PhoneBootstrapperBase
    {
        PhoneContainer container;

        public AppBootstrapper()
        {
            Start();
        }

        protected override void Configure()
        {
            container = new PhoneContainer();

            if (!Execute.InDesignMode)
                container.RegisterPhoneServices(RootFrame);

            container.Instance<ProgressService>(new ProgressService(RootFrame));

            container.Singleton<StorageService>();

            container.PerRequest<MainPageViewModel>();
            container.PerRequest<ProxySettingPageViewModel>();
            container.PerRequest<ProxySettingFinishPageViewModel>();

            AddCustomConventions();
        }

        static void AddCustomConventions()
        {
            ConventionManager.AddElementConvention<BindableAppBarButton>(
            Control.IsEnabledProperty, "DataContext", "Click");
            ConventionManager.AddElementConvention<BindableAppBarMenuItem>(
            Control.IsEnabledProperty, "DataContext", "Click");
        }

        protected override object GetInstance(Type service, string key)
        {
            var instance = container.GetInstance(service, key);
            if (instance != null)
                return instance;

            throw new Exception("Could not locate any instances.");
        }

        protected override IEnumerable<object> GetAllInstances(Type service)
        {
            return container.GetAllInstances(service);
        }

        protected override void BuildUp(object instance)
        {
            container.BuildUp(instance);
        }
    }
}
